<script setup lang="ts">
  import { useGetAllGoodTypeOptions } from '@/services/pages/good/useType'
  import { TableInstance } from 'element-plus'
  import { ref, watch } from 'vue'

  defineOptions({
    name: 'GoodTypeSelectFeeStandardCreate',
  })

  const { options, getOptionsLoading, getOptions } = useGetAllGoodTypeOptions()

  const emits = defineEmits<{
    (e: 'confirm', value: Array<GoodTypeOptions>): void
  }>()

  // 抽屉显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 表格数据
  const tableData = ref<Array<{ id: string; name: string }>>([])

  // 产品分类选择列表
  const selectedGoodTypes = ref<Array<GoodTypeOptions>>([])

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  /**
   * 分类选择事件
   * @param {Array} _selectedGoodTypes - 产品分类选择列表
   */
  const handleSelect = (_selectedGoodTypes: Array<GoodTypeOptions>) => {
    selectedGoodTypes.value = _selectedGoodTypes
  }

  /**
   * 关闭抽屉
   */
  const closeDrawer = () => {
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = () => {
    emits('confirm', selectedGoodTypes.value)
    closeDrawer()
  }

  watch(visible, (value) => {
    if (value) {
      getOptions().then(() => {
        tableData.value.length = 0
        options.value.forEach((goodType) => {
          goodType.childData.forEach((secondLevelGoodType) => {
            let item = { ...secondLevelGoodType, parentId: goodType.id }
            tableData.value.push(item)
          })
        })
      })
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    title="选择产品分类"
    :width="600"
    unit="px"
    :loading="getOptionsLoading"
  >
    <el-table
      height="100%"
      :data="tableData"
      :border="true"
      @select="handleSelect"
      @select-all="handleSelect"
      ref="tableInstance"
      :stripe="true"
    >
      <el-table-column type="selection" width="50" :align="'center'" fixed="left"></el-table-column>
      <el-table-column
        type="index"
        width="50"
        :align="'center'"
        fixed="left"
        label="序号"
      ></el-table-column>
      <el-table-column label="产品分类" prop="name"></el-table-column>
    </el-table>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="closeDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>
